/**
 * Copyright ©2016-2020 northkingbpo Corporation, All Rights Reserved
 * http://www.northkingbpo.net/
 */
package profile.hujia.log.analysis.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * class info
 *
 * @author hujia
 * @date 2018/12/18 15:37
 */
@Slf4j
@Service
public class FileManageImpl implements FileManage {

    @Override
    public void checkFilePath(String path) throws Exception {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    @Override
    public String generateFileName(String fileExtension) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = simpleDateFormat.format(date) + fileExtension;
        return fileName;
    }

    @Override
    public void save(String path, String fileExtension, StringBuilder text) throws Exception {
        checkFilePath(path);
        String filePath = path + generateFileName(fileExtension);
        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
            fileOutputStream.write(text.toString().getBytes());
        } catch (Exception e) {
            log.error("write file error.", e);
        }
    }


}
